package cn.humaohua.study.yanmo_design_pattern.ch15.v4;

import java.util.ArrayList;
import java.util.List;

public class Composite extends Component {

    private List<Component> childComponents = null;

    private String name = "";

    public Composite(String name) {
        this.name = name;
    }

    @Override
    public void addChild(Component child) {
        if (childComponents == null)
            childComponents = new ArrayList<>();
        childComponents.add(child);

        if (this.getComponentPath() == null || this.getComponentPath().trim().length() == 0) {
            this.setComponentPath(this.name);
        }

        if (this.getComponentPath().startsWith(child.getName() + ".")) {
            throw new IllegalArgumentException(String.format("在本通路上，组件%s 已经被添加了", child.getName()));
        } else {
            if (this.getComponentPath().indexOf("." + child.getName()) < 0) {
                String componentPath = this.childComponents + "." + child.getName();
                child.setComponentPath(componentPath);
            } else {
                throw new IllegalArgumentException(String.format("在本通路上，组件%s 已经被添加了", child.getName()));
            }
        }
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void printStruct(String preStr) {
        System.out.println(preStr + "_" + this.name);
        if (this.childComponents != null) {
            preStr += " ";
            for (Component c : this.childComponents) {
                c.printStruct(preStr);
            }
        }
    }
}
